
#include <iostream>
#include <string>
#include "Reactor.hpp"
#include "Listen.hpp"
#include "Protocol.hpp"
#include "NetCal.hpp"

int main(int argc,char* argv[])
{
    if(argc!=2)
    {
        std::cout<<"Usage: ./Reactorserver port"<<std::endl;
        return 1;
    }
    int port=std::stoi(argv[1]);

    //业务模块
    std::shared_ptr<Cal> cal=std::make_shared<Cal>();
    //协议模块
    std::shared_ptr<Protocol> protocol=std::make_shared<Protocol>([&cal](Request& req)->Response{
        return cal->Execute(req); //根据请求构建响应
    });
    
    //构建listen对象
    std::shared_ptr<Connection> conn=std::make_shared<Listen>(port);
    //注册一个消息处理函数
    conn->RegisterHanlder([&protocol](std::string& inbuffer)->std::string{
        std::string response_str;
        while(true)
        {
            std::string package;
            if(!protocol->Decode(inbuffer,&package))
            break;
            response_str+=protocol->Execute(package);//构建响应并序列化
        }
        return response_str;//得到序列化之后的结果
    });
    
    //构建Reactor服务
    std::unique_ptr<Reactor> R=std::make_unique<Reactor>();
    R->AddConnection(conn);
    R->loop();

    return 0;
}